<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LeanCloud画板</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/mdui@1.0.2/dist/css/mdui.min.css">
    <style>
        #drawing-panel {
            margin-top: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }

        #drawing-canvas {
            width: 100%;
            height: 500px;
            background-color: white;
            cursor: crosshair;
        }

        .mdui-tab {
            margin-bottom: 20px;
        }

        .mdui-dialog-content {
            padding: 20px;
        }

        #auth-text {
            margin-left: 8px;
        }
    </style>
</head>
<body class="mdui-theme-primary-blue mdui-theme-accent-blue">
    <div class="mdui-container">
        <!-- 登录/注册对话框 -->
        <div class="mdui-dialog" id="auth-dialog">
            <div class="mdui-dialog-title">登录/注册</div>
            <div class="mdui-dialog-content">
                <div class="mdui-tab mdui-tab-scrollable" id="auth-tab">
                    <a href="#login-panel" class="mdui-ripple mdui-tab-active">登录</a>
                    <a href="#register-panel" class="mdui-ripple">注册</a>
                </div>
                
                <div id="login-panel">
                    <div class="mdui-textfield">
                        <label class="mdui-textfield-label">用户名</label>
                        <input class="mdui-textfield-input" type="text" id="login-username" required/>
                    </div>
                    <div class="mdui-textfield">
                        <label class="mdui-textfield-label">密码</label>
                        <input class="mdui-textfield-input" type="password" id="login-password" required/>
                    </div>
                </div>
                
                <div id="register-panel" style="display: none;">
                    <div class="mdui-textfield">
                        <label class="mdui-textfield-label">用户名</label>
                        <input class="mdui-textfield-input" type="text" id="register-username" required/>
                    </div>
                    <div class="mdui-textfield">
                        <label class="mdui-textfield-label">邮箱</label>
                        <input class="mdui-textfield-input" type="email" id="register-email" required/>
                    </div>
                    <div class="mdui-textfield">
                        <label class="mdui-textfield-label">密码</label>
                        <input class="mdui-textfield-input" type="password" id="register-password" required/>
                    </div>
                </div>
            </div>
            <div class="mdui-dialog-actions">
                <button class="mdui-btn mdui-ripple" id="cancel-auth">取消</button>
                <button class="mdui-btn mdui-ripple" id="confirm-auth">确认</button>
            </div>
        </div>

        <!-- 主界面 -->
        <div class="mdui-appbar">
            <div class="mdui-toolbar mdui-color-theme">
                <span class="mdui-typo-title">LeanCloud画板</span>
                <div class="mdui-toolbar-spacer"></div>
                <button id="auth-btn" class="mdui-btn mdui-btn-raised mdui-ripple">
                    <i class="mdui-icon material-icons">account_circle</i>
                    <span id="auth-text">登录/注册</span>
                </button>
                <button id="save-btn" class="mdui-btn mdui-btn-raised mdui-ripple mdui-color-accent" disabled>
                    <i class="mdui-icon material-icons">save</i>
                    <span>保存</span>
                </button>
                <button id="clear-btn" class="mdui-btn mdui-btn-raised mdui-ripple">
                    <i class="mdui-icon material-icons">clear</i>
                    <span>清空</span>
                </button>
            </div>
        </div>

        <div class="mdui-panel" id="drawing-panel">
            <canvas id="drawing-canvas"></canvas>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/mdui@1.0.2/dist/js/mdui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/leancloud-storage@4.12.0/dist/av-min.js"></script>
    <script>
        // LeanCloud 初始化
        const APP_ID = 'jyP5Gj0JKvrrBEJAqcTPE7Cl-gzGzoHsz';
        const APP_KEY = 'sRT5sxlomwR7VTg9zNJFCURv';
        const SERVER_URL = 'https://jyp5gj0j.lc-cn-n1-shared.com';

        AV.init({
            appId: APP_ID,
            appKey: APP_KEY,
            serverURLs: SERVER_URL
        });

        // 全局变量
        let currentUser = null;
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;
        let hue = 0;
        let direction = true;

        // DOM元素
        const canvas = document.getElementById('drawing-canvas');
        const ctx = canvas.getContext('2d');
        const authDialog = new mdui.Dialog('#auth-dialog');
        const authTab = new mdui.Tab('#auth-tab');
        const authBtn = document.getElementById('auth-btn');
        const authText = document.getElementById('auth-text');
        const saveBtn = document.getElementById('save-btn');
        const clearBtn = document.getElementById('clear-btn');
        const cancelAuthBtn = document.getElementById('cancel-auth');
        const confirmAuthBtn = document.getElementById('confirm-auth');

        // 初始化画布
        function initCanvas() {
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;
            
            ctx.strokeStyle = '#BADA55';
            ctx.lineJoin = 'round';
            ctx.lineCap = 'round';
            ctx.lineWidth = 5;
        }

        // 绘图函数
        function draw(e) {
            if (!isDrawing) return;
            
            ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(e.offsetX, e.offsetY);
            ctx.stroke();
            
            [lastX, lastY] = [e.offsetX, e.offsetY];
            
            hue++;
            if (hue >= 360) hue = 0;
            
            if (ctx.lineWidth >= 50 || ctx.lineWidth <= 1) {
                direction = !direction;
            }
            
            if (direction) {
                ctx.lineWidth++;
            } else {
                ctx.lineWidth--;
            }
        }

        // 保存绘图到LeanCloud
        async function saveDrawing() {
            if (!currentUser) return;
            
            const dataURL = canvas.toDataURL('image/png');
            
            const Drawing = AV.Object.extend('Drawing');
            const drawing = new Drawing();
            
            drawing.set('image', dataURL);
            drawing.set('author', currentUser);
            
            try {
                await drawing.save();
                mdui.snackbar({
                    message: '保存成功',
                    position: 'right-top'
                });
            } catch (error) {
                console.error('保存失败:', error);
                mdui.snackbar({
                    message: '保存失败: ' + error.message,
                    position: 'right-top'
                });
            }
        }

        // 加载用户绘图
        async function loadUserDrawing() {
            if (!currentUser) return;
            
            const query = new AV.Query('Drawing');
            query.equalTo('author', currentUser);
            query.descending('createdAt');
            
            try {
                const result = await query.first();
                if (result) {
                    const img = new Image();
                    img.onload = function() {
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        ctx.drawImage(img, 0, 0);
                    };
                    img.src = result.get('image');
                }
            } catch (error) {
                console.error('加载失败:', error);
            }
        }

        // 清空画布
        function clearCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }

        // 用户登录
        async function login(username, password) {
            try {
                currentUser = await AV.User.logIn(username, password);
                updateUIAfterLogin();
                mdui.snackbar({
                    message: '登录成功',
                    position: 'right-top'
                });
                loadUserDrawing();
            } catch (error) {
                console.error('登录失败:', error);
                mdui.snackbar({
                    message: '登录失败: ' + error.message,
                    position: 'right-top'
                });
            }
        }

        // 用户注册
        async function register(username, email, password) {
            const user = new AV.User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPassword(password);
            
            try {
                currentUser = await user.signUp();
                updateUIAfterLogin();
                mdui.snackbar({
                    message: '注册成功',
                    position: 'right-top'
                });
            } catch (error) {
                console.error('注册失败:', error);
                mdui.snackbar({
                    message: '注册失败: ' + error.message,
                    position: 'right-top'
                });
            }
        }

        // 用户登出
        function logout() {
            AV.User.logOut();
            currentUser = null;
            updateUIAfterLogout();
            mdui.snackbar({
                message: '已登出',
                position: 'right-top'
            });
        }

        // 更新登录后的UI
        function updateUIAfterLogin() {
            authText.textContent = currentUser.getUsername();
            saveBtn.disabled = false;
            authBtn.onclick = logout;
        }

        // 更新登出后的UI
        function updateUIAfterLogout() {
            authText.textContent = '登录/注册';
            saveBtn.disabled = true;
            authBtn.onclick = showAuthDialog;
        }

        // 显示登录对话框
        function showAuthDialog() {
            authDialog.open();
        }

        // 检查当前用户
        function checkCurrentUser() {
            currentUser = AV.User.current();
            if (currentUser) {
                updateUIAfterLogin();
                loadUserDrawing();
            } else {
                updateUIAfterLogout();
            }
        }

        // 事件监听
        canvas.addEventListener('mousedown', (e) => {
            isDrawing = true;
            [lastX, lastY] = [e.offsetX, e.offsetY];
        });

        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', () => isDrawing = false);
        canvas.addEventListener('mouseout', () => isDrawing = false);

        authBtn.addEventListener('click', showAuthDialog);
        saveBtn.addEventListener('click', saveDrawing);
        clearBtn.addEventListener('click', clearCanvas);

        cancelAuthBtn.addEventListener('click', () => authDialog.close());

        confirmAuthBtn.addEventListener('click', () => {
            const activeTab = document.querySelector('.mdui-tab-active').getAttribute('href');
            
            if (activeTab === '#login-panel') {
                const username = document.getElementById('login-username').value;
                const password = document.getElementById('login-password').value;
                login(username, password);
            } else {
                const username = document.getElementById('register-username').value;
                const email = document.getElementById('register-email').value;
                const password = document.getElementById('register-password').value;
                register(username, email, password);
            }
            
            authDialog.close();
        });

        // 初始化
        window.addEventListener('load', () => {
            initCanvas();
            checkCurrentUser();
        });

        window.addEventListener('resize', initCanvas);
    </script>
</body>
</html>